package com.yc.springmvc.web;

import com.google.gson.Gson;
import com.yc.springmvc.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //控制器方法=》适配器对象
        System.out.println("handler = " + handler);
        Object loginedUser = request.getSession().getAttribute("loginedUser");
        if(loginedUser == null){
            if (request.getRequestURI().endsWith(".do")){
                //ajax axjax 请求
                //请求转发
                //RequestDispatcher rd = request.getRequestDispatcher("/nologin.action");
                //rd.forward(request,response);
                response.setContentType("application/json;charset=utf-8");
                Gson gson = new Gson();
                Result result = new Result(0,"请先登录系统", null);
                String j = gson.toJson(result);
                response.getWriter().append(j);
            }else{
                //普通请求
                //contextPath => 上下文路径  =》 工程名
                String contextPath = request.getContextPath();
                //跳转登录页的绝对路径
                response.sendRedirect(contextPath + "/login.html");
            }
            return false;
        }else {
            return true;
        }
    }
}
